﻿using System;
using System.Activities;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TransactionServer.General_Classes;
using Microsoft.VisualBasic.Activities;

namespace TransactionServer.ActivityDesign
{
    public partial class FilterEdit
    {
        TreeViewItem attributesNode = new TreeViewItem() { Header = "атрибуты", Name = "attributes" };
        TreeViewItem filterNode = new TreeViewItem() { Header = "фильтры", Name = "filters" };
        TreeViewItem linkEntityNode = new TreeViewItem() { Header = "связанные сущности", Name = "linkentities" };

        public FilterEdit()
        {
            InitializeComponent();
            filterEdit.Items.Add(attributesNode);
            filterEdit.Items.Add(filterNode);
            filterEdit.Items.Add(linkEntityNode);

            //InArgument<Filter> filter = new InArgument<Filter>(new VisualBasicValue<Filter>(toString()));
  

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (filterEdit.SelectedValue is TreeViewItem)
            {
                var selectedItem = (TreeViewItem)filterEdit.SelectedValue;
                object item = null;

                if (selectedItem != null)
                {
                    switch ((selectedItem).Name)
                    {
                        case "attributes":
                            item = new CAttribute("\"name\"");
                            selectedItem.Items.Add(item);
                            break;
                        case "filters":
                            item = new CCondition("\"name\"", "=", "");
                            selectedItem.Items.Add(item);
                            break;
                        case "linkentities":
                            item = new CLinkEntity("\"entityfrom\"", "\"attributefrom\"", "\"entityto\"", "\"attributeto\"");
                            selectedItem.Items.Add(item);
                            break;
                        default:
                            break;
                    }

                    if (item != null)
                    {
                        selectedItem.IsExpanded = true;
                    }
                }
            }
        }

        private void UpdateValue(object value)
        {
            int i = 0;

            if (value is CAttribute)
            {
                i = attributesNode.Items.IndexOf(value);
                if (i >= 0)
                {
                    attributesNode.Items.Remove(value);
                    attributesNode.Items.Insert(i, value);
                }
            }
            else if (value is CCondition)
            {
                i = filterNode.Items.IndexOf(value);
                if (i >= 0)
                {
                    filterNode.Items.Remove(value);
                    filterNode.Items.Insert(i, value);
                }
            }
            else if (value is CLinkEntity)
            {
                i = linkEntityNode.Items.IndexOf(value);
                if (i >= 0)
                {
                    linkEntityNode.Items.Remove(value);
                    linkEntityNode.Items.Insert(i, value);
                }
            }
        }

        private void filterEdit_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            UpdateValue(e.OldValue);

            var selectedItem = filterEdit.SelectedValue;

            if (selectedItem != null)
            {
                if (selectedItem is CAttribute)
                {
                    var s = (CAttribute)filterEdit.SelectedValue;
                    ContentFrame.Navigate(new EditAttribute(ref s));
                }
                else if (selectedItem is CCondition)
                {
                    var f = (CCondition)filterEdit.SelectedValue;
                    ContentFrame.Navigate(new EditFilter(ref f));
                }
                else if (selectedItem is CLinkEntity)
                {
                    var le = (CLinkEntity)filterEdit.SelectedValue;
                    ContentFrame.Navigate(new EditLinkEntity(ref le));
                }
                else
                {
                    ContentFrame.Navigate(null);
                }
            }

            InArgument<Filter> filter = new InArgument<Filter>(new VisualBasicValue<Filter>(toString()));
            this.ModelItem.Properties["Filter"].SetValue(filter);
        }

        private void btnSub_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = filterEdit.SelectedValue;

            if (selectedItem is CAttribute)
            {
                attributesNode.Items.Remove(selectedItem);
            }
            else if (selectedItem is CCondition)
            {
                filterNode.Items.Remove(selectedItem);
            }
            else if (selectedItem is CLinkEntity)
            {
                linkEntityNode.Items.Remove(selectedItem);
            }
        }

        private string toString()
        {
            StringBuilder result = new StringBuilder();

            
            bool coma = false;
            result.Append("New TransactionServer.General_Classes.Filter(New System.Collections.Generic.List(Of TransactionServer.General_Classes.CAttribute) (New TransactionServer.General_Classes.CAttribute() { _\n _\n _\n");
            foreach (CAttribute attribute in attributesNode.Items)
            {
                if (coma)
                {
                    result.Append(",");
                }
                result.AppendFormat(" _\n _\nNew TransactionServer.General_Classes.CAttribute( _\n{0} _\n) _\n _\n", attribute.name);
                coma = true;
            }
            result.Append(" _\n _\n _\n})");

            coma = false;
            result.Append(",New System.Collections.Generic.List(Of TransactionServer.General_Classes.CCondition) (New TransactionServer.General_Classes.CCondition() { _\n _\n _\n");
            foreach (CCondition condition in filterNode.Items)
            {
                if (coma)
                {
                    result.Append(",");
                }
                result.AppendFormat(" _\n _\nNew TransactionServer.General_Classes.CCondition( _\n{0} _\n, _\n\"{1}\" _\n, _\n{2} _\n) _\n _\n", condition.attribute, condition.opr, condition.value);
                coma = true;
            }
            result.Append(" _\n _\n _\n})");

            coma = false;
            result.Append(",New System.Collections.Generic.List(Of TransactionServer.General_Classes.CLinkEntity) (New TransactionServer.General_Classes.CLinkEntity() { _\n _\n _\n");
            foreach (CLinkEntity linkentity in linkEntityNode.Items)
            {
                if (coma)
                {
                    result.Append(",");
                }
                result.AppendFormat(" _\n _\nNew TransactionServer.General_Classes.CLinkEntity( _\n{0} _\n, _\n{1} _\n, _\n{2} _\n, _\n{3} _\n) _\n _\n", linkentity.entityfrom, linkentity.attributefrom, linkentity.entityto, linkentity.attributeto);
                coma = true;
            }
            result.Append(" _\n _\n _\n}))");
            
            return result.ToString();
        }

        private void ActivityDesigner_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.ModelItem.Properties["Filter"].Value != null)
                {
                    var filter = (VisualBasicValue<Filter>)((InArgument<Filter>)this.ModelItem.Properties["Filter"].Value.GetCurrentValue()).Expression;
                    var s = filter.ExpressionText;

                    var arrays = s.Split(new string[] { " _\n _\n _\n" }, StringSplitOptions.None);
                    string[] elements;

                    if (!string.IsNullOrEmpty(arrays[1]))
                    {
                        elements = arrays[1].Split(new string[] {" _\n _\n"}, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string element in elements)
                        {
                            string[] parameters = element.Split(new string[] { " _\n" }, StringSplitOptions.RemoveEmptyEntries);
                            attributesNode.Items.Add(new CAttribute(parameters[1]));
                        }
                    }

                    if (!string.IsNullOrEmpty(arrays[3]))
                    {
                        elements = arrays[3].Split(new string[] { " _\n _\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string element in elements)
                        {
                            string[] parameters = element.Split(new string[] { " _\n" }, StringSplitOptions.RemoveEmptyEntries);
                            filterNode.Items.Add(new CCondition(parameters[1], parameters[3].Replace("\"", ""), parameters[5]));
                            
                        }
                    }

                    if (!string.IsNullOrEmpty(arrays[5]))
                    {
                        elements = arrays[5].Split(new string[] { " _\n _\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string element in elements)
                        {
                            string[] parameters = element.Split(new string[] { " _\n" }, StringSplitOptions.RemoveEmptyEntries);
                            linkEntityNode.Items.Add(new CLinkEntity(parameters[1], parameters[3], parameters[5], parameters[7]));
                        }
                    }
                }
            }
            catch { };
        }
    }

}
